package com.musiklegal;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.MalformedURLException;
import java.net.URL;

import javax.xml.parsers.ParserConfigurationException;
import javax.xml.parsers.SAXParser;
import javax.xml.parsers.SAXParserFactory;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;
import org.xml.sax.InputSource;
import org.xml.sax.SAXException;
import org.xml.sax.XMLReader;

import android.app.Activity;
import android.app.AlertDialog;
import android.app.Dialog;
import android.app.ProgressDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.Bitmap;
import android.os.Bundle;
import android.os.Handler;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

public class Browseby extends Activity {
	
	static int pos;
	HttpClient mlist;
	HttpGet get;
	HttpResponse mresp ;
	HttpEntity merclist;
	SAXParserFactory spf;
	SAXParser sp;
	XMLReader xr;
	CatalogueParser cp;
	AlertDialog.Builder alert;
	ImageView mc;
	static String methods;
	static String []eras={"1", "2" , "3", "4",   "5",  "6", "7",};
	static String [] period={"60","70","80","90","2000","2010","2011"};
	static String apikey;
	static String imurl;
	static String name;
	TextView tv;
	Handler h;
	ProgressDialog dialog;
	protected Dialog onCreateDialog(int id) {
        switch (id) {
              case 0: {
                    dialog = new ProgressDialog(this);
                    dialog.setMessage("Loading...");
                    dialog.setIndeterminate(true);
                    dialog.setCancelable(true);
                    return dialog;                   
              }
        }
        return null;
  }
	
	public void onCreate(Bundle savedInstanceState) 
    {
		h = new Handler();
		new Thread(new Runnable(){

			public void run() {
				// TODO Auto-generated method stub
				
				 if(!MusikLegal.internet(getApplicationContext()))
				 {
					 h.post(new Runnable(){

						public void run() {
							// TODO Auto-generated method stub
							 finish();
						}});
					
				 }
			}}).start();
	
	 
        super.onCreate(savedInstanceState);
        setContentView(R.layout.browse);
        tv = (TextView)findViewById(R.id.onlinestore);
		tv.setText(name);
        Button top = (Button) this.findViewById(R.id.top);
        Button newr = (Button) this.findViewById(R.id.newr);
        Button genre = (Button) this.findViewById(R.id.genre);
        Button origin = (Button) this.findViewById(R.id.origin);
        Button era = (Button) this.findViewById(R.id.era);
        Button artist = (Button) this.findViewById(R.id.art);
        mc = (ImageView) findViewById(R.id.header);
        
        Bitmap p = null ;
		String url = imurl;
		if(url!=null)
			p= loadImage(url);
		if(p!=null)
			mc.setImageBitmap(p);
		else
			mc.setImageResource(R.drawable.header);
        
       // top.setBackgroundDrawable(mc.getDrawable());
        top.setOnClickListener(new OnClickListener() {
			
			public void onClick(View arg0) {
				methods="get";
				
				new Thread(new Runnable(){

					public void run() {
						h.post(new Runnable(){

							public void run() {
								// TODO Auto-generated method stub
								showDialog(0);
							}});
								
								method(pos,methods);
								h.post(new Runnable(){

									public void run() {
										// TODO Auto-generated method stub
										removeDialog(0);
									}});
								
							
						
					}}).start();
    			
			}

		});
        newr.setOnClickListener(new OnClickListener() {
			
			public void onClick(View arg0) {
				methods="new_release";
				showDialog(0);
				new Thread(new Runnable(){

					public void run() {
						h.post(new Runnable(){

							public void run() {
								method(pos,methods);
								removeDialog(0);
							}});
						
					}}).start();
			
			}

		});
        
        genre.setOnClickListener(new OnClickListener() {
	
        	public void onClick(View arg0) {
        		
        	
        		
       		        showDialog(0);
       				new Thread(new Runnable(){

    					public void run() {
    						
    								if(MusikLegal.internet(getApplicationContext())){
    					       			
    								 try{

    				       					HttpClient mlist = new DefaultHttpClient(); 
    				       					HttpGet get = new HttpGet("http://secure.musiklegal.com/?action=catalogue&method=genre"+"&api_key="+apikey);
    				       					HttpResponse mresp = mlist.execute(get);

    				       					HttpEntity merclist = mresp.getEntity();
    				       					SAXParserFactory spf = SAXParserFactory.newInstance();
    				       					SAXParser sp = spf.newSAXParser();
    				       					XMLReader xr = sp.getXMLReader();
    				       					 
    				       					BrowsePar xmlr = new BrowsePar();
    				       					xr.setContentHandler(xmlr);
    				       					xr.parse(retrieveInputStream(merclist)); 
    				       					
    				       					Browse bw = xmlr.getBrowse();
    				       				
    				       					Songby.list=bw.getGen().split("fachr1");
    				       					Songby.method="&genre=";
    				       					
    				       			 	}
    				       				 catch (Exception e) {
    				       					 
    				       			        }
    				       				h.post(new Runnable(){

    		    							public void run() {
    				       				startActivity(new Intent(getApplicationContext(),Songby.class));
    		    							}});
    							 }
    			        		else
    			        			{
    			        			h.post(new Runnable(){

		    							public void run() {
    			        				Toast.makeText(getApplicationContext(), Settings.gakonek, Toast.LENGTH_SHORT).show();
    			        				finish();
		    							}});
    			        			}
    								h.post(new Runnable(){

		    							public void run() {
    								removeDialog(0);
		    							}});
    							
    						
    					}}).start();
       				
       			
        		
        		
        	}

        });
        origin.setOnClickListener(new OnClickListener() {
			
			public void onClick(View arg0) {
				
				new Thread(new Runnable(){

					public void run() {
						h.post(new Runnable(){

							public void run() {
								// TODO Auto-generated method stub
								showDialog(0);
							}});
						
								if(MusikLegal.internet(getApplicationContext())){
					       			 try{
					       		        	
					       					HttpClient mlist = new DefaultHttpClient(); 
					       					HttpGet get = new HttpGet("http://secure.musiklegal.com/?action=catalogue&method=get_origin"+"&api_key="+apikey);
					       					HttpResponse mresp = mlist.execute(get);
					       					
					       					HttpEntity merclist = mresp.getEntity();
					       					SAXParserFactory spf = SAXParserFactory.newInstance();
					       					SAXParser sp = spf.newSAXParser();
					       					XMLReader xr = sp.getXMLReader();
					       					 
					       					BrowsePar xmlr = new BrowsePar();
					       					xr.setContentHandler(xmlr);
					       					xr.parse(retrieveInputStream(merclist)); 
					       					
					       					Browse bw = xmlr.getBrowse();
					       				
					       					Songby.list=bw.getOri().split("fachr1");
					       					Songby.method="&origin=";
					       					
					       			 	}
					       				 catch (Exception e) {
					       					 
					       			        }
					       				h.post(new Runnable(){

											public void run() {
					       				startActivity(new Intent(getApplicationContext(),Songby.class));
					       		        }});
					       			 }
								else
								{
									h.post(new Runnable(){

										public void run() {
											// TODO Auto-generated method stub
										Toast.makeText(getApplicationContext(), Settings.gakonek, Toast.LENGTH_SHORT).show();
									finish();	
										}});
									
								}
								h.post(new Runnable(){

									public void run() {
										// TODO Auto-generated method stub
									removeDialog(0);
	
									}});
							
					}}).start();
					
	        	}

		});
        era.setOnClickListener(new OnClickListener() {
			
			public void onClick(View arg0) 
			{
				
				new Thread(new Runnable(){

					public void run() {
						h.post(new Runnable(){

							public void run() {
								// TODO Auto-generated method stub
								showDialog(0);
							}});
						
								
								if(MusikLegal.internet(getApplicationContext())){
									Songby.list=period;
									Songby.daftar=eras;
									Songby.era=true;
									Songby.method="&period=";
									h.post(new Runnable(){

										public void run() {
					        		startActivity(new Intent(getApplicationContext(),Songby.class));
										}});
								}
								else
									{
									h.post(new Runnable(){

										public void run() {
											// TODO Auto-generated method stub
											Toast.makeText(getApplicationContext(), Settings.gakonek, Toast.LENGTH_SHORT).show();
											finish();
										}});
										
									}
								h.post(new Runnable(){

									public void run() {
										// TODO Auto-generated method stub
										removeDialog(0);
									}});
								
								
							
						
					}}).start();
				
				
		        
			}
		});
        	artist.setOnClickListener(new OnClickListener() {
			
			public void onClick(View arg0) {
				new Thread(new Runnable(){

					public void run() {
						if(MusikLegal.internet(getApplicationContext())){
							h.post(new Runnable(){

								public void run() {
									// TODO Auto-generated method stub
								startActivity(new Intent(getApplicationContext(),Artist.class));	
								}});
							
						}
						else
						{
							h.post(new Runnable(){

								public void run() {
									// TODO Auto-generated method stub
									Toast.makeText(getApplicationContext(), Settings.gakonek, Toast.LENGTH_SHORT).show();
									finish();
								}});
							
						}
						
					}}).start();
				
					
		        
			}

		});
    
    }
	
	void method(int position, String method)
	{
		if(MusikLegal.internet(getApplicationContext())){
		try 
		{
    		OnlineC.catl.clear();
    		String p = "http://secure.musiklegal.com/?action=catalogue&method="+method+"&api_key="+apikey+"&limit=25&offset=";
    		Address addr = new Address("http://secure.musiklegal.com/?action=catalogue&method="+method+"&api_key="+apikey+"&limit=25",1,"");
    		//Log.i("alamat ", p);
    		get = new HttpGet(addr.toString());
    		mlist = new DefaultHttpClient();
    		spf = SAXParserFactory.newInstance();
    		sp = spf.newSAXParser();
    		CatalogueList.addres = addr;
    		CatalogueList.merchant = OnlineC.merch.get(position);
			mresp = mlist.execute(get);
			merclist= mresp.getEntity();
			xr = sp.getXMLReader();
    		cp = new CatalogueParser();
    		xr.setContentHandler(cp);
    		xr.parse(retrieveInputStream(merclist));
    		OnlineC.catl.addAll(cp.catl);
		} 
		catch (ClientProtocolException e) {
			
			e.printStackTrace();
			finish();
		} catch (IOException e) {
			
			e.printStackTrace();
			finish();
		}
		catch (SAXException e) {
			
			e.printStackTrace();
			finish();
			
		} catch (ParserConfigurationException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		CatalogueList.thismerchant =OnlineC.merch.get(position);
	
	
		startActivity(new Intent(getApplicationContext(),CatalogueList.class));
		}
		else 
		{
		        AlertDialog alertDialog = new AlertDialog.Builder(this).create();
				alertDialog.setTitle("Error");
				alertDialog.setMessage(Settings.gakonek);
				alertDialog.setButton("OK", new DialogInterface.OnClickListener() { 
					public void onClick(DialogInterface dialog, int which) {
					finish();
					}
				});
				alertDialog.setIcon(R.drawable.oc2);
				alertDialog.show();
		        }
			
		
		
	}
	private InputSource retrieveInputStream(HttpEntity httpEntity) {
        InputSource insrc = null;
        try {
              insrc = new InputSource(httpEntity.getContent());
        } catch (Exception e) {
        }
        return insrc;
  }
	
	Bitmap loadImage(String url)
	 {
		 File cache = new File(MusikLegal.cacheFolder,"tempp");
			InputStream is = null;
			Bitmap bitmap;
			
				try {

					

					is = new URL(url).openStream();
					 OutputStream os = new FileOutputStream(cache);
			            Utils.CopyStream(is, os);
			            os.close();
			            bitmap = TrackInfo.decodeFile(cache);
			            is.close();
			            return bitmap;
					
				

				} 
				catch (MalformedURLException e) {
					Log.d("gambar","error "+e.getMessage() );
					e.printStackTrace();
					return null;
				} catch (IOException e) {
					
					Log.d("gambar","error "+e.getMessage() );
					e.printStackTrace();
					return null;
				}
				
				
			
	 }
}
